<template>
  <div class="login">
    <div class="content" v-if="!is_change_succeed">
      <img
        src="https://img.zcool.cn/community/0193dc5b9a0366a8012099c8281b5d.jpg@1280w_1l_2o_100sh.jpg"
        class="logo"
      />
      <div class="top_content">
        <h3>找回密码</h3>
      </div>
      <div class="forgot_content">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
          size="large"
        >
          <el-form-item label="手机号" prop="phone_number">
            <el-input
              v-model="ruleForm.phone_number"
              autocomplete="off"
              placeholder="请输入绑定手机号"
            />
          </el-form-item>
          <div class="captcha">
            <div class="left_captcha">
              <el-form-item label="验证码" prop="checkPass">
                <el-input
                  v-model="ruleForm.checkPass"
                  autocomplete="off"
                  placeholder="请输入验证码"
                />
              </el-form-item>
            </div>
            <div class="get_captcha">
              <button
                class="getCaptcha"
                id="CaptchaId"
                type="button"
                v-show="!isSend"
              >
                获取验证码
              </button>
              <button class="captchaSend" type="button" v-show="isSend">
                {{ time }}秒后重新获取
              </button>
            </div>
          </div>
          <el-form-item label="新密码" prop="passWord" :inline-message="true">
            <el-input
              v-model="ruleForm.passWord"
              type="password"
              :show-password="true"
              autocomplete="new-passWord"
              placeholder="请输入密码"
            />
          </el-form-item>
          <div class="passWord_msg">
            格式为数字与字母不区分大小写，长度为6-12位，不包含特殊符号
          </div>
          <el-form-item label="确认密码" prop="newPassWord">
            <el-input
              v-model="ruleForm.newPassWord"
              type="password"
              :show-password="true"
              placeholder="请确保两次密码输入一致"
            />
          </el-form-item>
          <el-form-item class="submit_forgot_content">
            <a href="/login" class="go_login">登录</a>
            <el-button
              type="primary"
              @click="submitForm(ruleFormRef)"
              class="submit_forgot"
            >
              提交
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 修改密码成功时显示 -->
    <div class="succeed_msg" v-else>
      <img
        src="https://img.zcool.cn/community/0193dc5b9a0366a8012099c8281b5d.jpg@1280w_1l_2o_100sh.jpg"
        class="logo"
      />
      <div class="succeed_msg_content">
        <el-icon style="font-size: 65px; color: #52c41b">
          <CircleCheckFilled />
        </el-icon>
        <p>修改成功！</p>
        <a href="/login">去登陆</a>
      </div>
    </div>
    <div class="footer">CopyRight @ 优品汇 2015 - 2017</div>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
let axios: any = inject('$axios');

const ruleFormRef = ref<FormInstance>();
// 获取验证码倒计时
let isSend = ref(false);
// 倒计时时间
let time = ref(60);
// 修改成功出现成功提示弹框开关
let is_change_succeed = ref(false);
// 发送验证码
const getCaptcha = async (res: any) => {
  let date = await axios.getMaintainSendSms({
    mobile: ruleForm.phone_number,
  });
  //   let data = await request.getC(`${apiUrl()}/v2/utilities/mobile_captcha`, {
  //     mobile: ruleForm.number,
  //     captcha_type: 'event_pay_apply',
  //     ticket: res.ticket,
  //     randstr: res.randstr,
  //     version: 'v2'
  //   })
  if (date.data.code == 200) {
    isSend.value = true;
    let timer = setInterval(() => {
      time.value--;
      if (time.value == 0) {
        isSend.value = false;
        time.value = 60;
        clearInterval(timer);
      }
    }, 1000);
  }
};
function callback(res: any) {
  // 第一个参数传入回调结果，结果如下：
  // ret         Int       验证结果，0：验证成功。2：用户主动关闭验证码。
  // ticket      String    验证成功的票据，当且仅当 ret = 0 时 ticket 有值。
  // CaptchaAppId       String    验证码应用ID。
  // bizState    Any       自定义透传参数。
  // randstr     String    本次验证的随机串，后续票据校验时需传递该参数。
  console.log('callback:', res);
  getCaptcha(res);
}

const appid = '2079851433';
// 定义验证码js加载错误处理函数
function loadErrorCallback() {
  // 生成容灾票据或自行做其它处理
  var ticket =
    'terror_1001_' + appid + '_' + Math.floor(new Date().getTime() / 1000);
  callback({
    ret: 0,
    randstr: '@' + Math.random().toString(36).substr(2),
    ticket: ticket,
    errorCode: 1001,
    errorMessage: 'jsload_error',
  });
}

// 定义验证码触发事件
onMounted(() => {
  document.getElementById('CaptchaId').onclick = function () {
    ruleFormRef.value.validateField('phone_number', (verifycode_check) => {
      if (verifycode_check) {
        try {
          // 生成一个验证码对象
          // CaptchaAppId：登录验证码控制台，从【验证管理】页面进行查看。如果未创建过验证，请先新建验证。注意：不可使用客户端类型为小程序的CaptchaAppId，会导致数据统计错误。
          //callback：定义的回调函数
          var captcha = new TencentCaptcha(appid, callback, {});
          // 调用方法，显示验证码
          captcha.show();
        } catch (error) {
          // 加载异常，调用验证码js加载错误处理函数
          console.log(error, 'errorerrorerrorerror');

          loadErrorCallback();
        }
      }
    });
  };
});
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入验证码'));
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField('checkPass', () => null);
    }
    callback();
  }
};
let passWord_rule = new RegExp(/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,12}$/);
const validatePass_passWord = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (!passWord_rule.test(value)) {
    callback(new Error('输入格式有误'));
  } else {
    callback();
  }
};
let phoneReg = new RegExp(/^1[3456789]\d{9}$/);
const validatePass_phone_number = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入您的手机号码'));
  } else if (!phoneReg.test(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
};
const validatePass_new_passWord = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (value != ruleForm.passWord) {
    callback(new Error('两次密码不符'));
  } else {
    callback();
  }
};
const ruleForm = reactive({
  phone_number: '',
  checkPass: '',
  passWord: '',
  newPassWord: '',
});

const rules = reactive<FormRules<typeof ruleForm>>({
  phone_number: [
    { required: true, validator: validatePass_phone_number, trigger: 'blur' },
  ],
  checkPass: [{ required: true, validator: validatePass, trigger: 'blur' }],
  passWord: [
    { required: true, validator: validatePass_passWord, trigger: 'blur' },
  ],
  newPassWord: [
    { required: true, validator: validatePass_new_passWord, trigger: 'blur' },
  ],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let date = await axios.getMaintainUpdatePassword({
        mobile: ruleForm.phone_number,
        sms_code: ruleForm.checkPass,
        password: ruleForm.passWord,
      });
      if (date.data.code != 200)
        return ElMessage({
          message: date.data.message,
          type: 'error',
        });
      is_change_succeed.value = true;
    } else {
      console.log('error submit!');
      return false;
    }
  });
};
</script>

<style lang="scss" scoped>
.login {
  width: 100vw;
  height: 100vh;
  background: url('../assets/images/login/bg.png') no-repeat;
  background-size: 100% 100%;
  @include flex_cc();
  position: relative;

  .content {
    width: 500px;
    height: 470px;
    padding: 30px 20px;
    background: #fff;
    text-align: center;
    box-sizing: border-box;
    position: relative;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.14901960784313725);
    border-radius: 5px;

    .logo {
      width: 47px;
      position: absolute;
      top: 10px;
      left: 10px;
    }

    .top_content {
      display: flex;
      align-items: center;

      h3 {
        @include font(#333, 21, 20);
        font-weight: 650;
        flex: 1;
      }
    }

    .forgot_content {
      margin-top: 30px;

      .captcha {
        display: flex;

        .left_captcha {
          margin-right: 10px;
          width: 250px;
        }

        .get_captcha {
          flex: 1;

          button {
            display: block;
            height: 40px;
            background: rgb(58, 115, 253);
            border: none;
            color: #fff;
            border-radius: 5px;
            width: 100%;
            cursor: pointer;
            font-size: 12px;
          }

          .captchaSend {
            background-color: #fff;
            border: 1px solid #d8d8d8;
            color: #d8d8d8;
            cursor: not-allowed;
          }
        }
      }

      .passWord_msg {
        @include font(#aaa, 12, 21);
        padding-left: 80px;
        text-align: left;
        margin-top: -20px;
        margin-bottom: 10px;
      }

      .go_login {
        width: 140px;
        height: 40px;
        border: 1px solid rgb(0, 121, 254);
        border-radius: 5px;
        color: rgb(0, 121, 254);
      }

      .submit_forgot {
        width: 140px;
        height: 40px;
        margin-left: 20px;
      }

      .submit_forgot_content {
        margin-top: 40px;

        :deep(.el-form-item__content) {
          justify-content: center;
        }
      }
    }
  }
  .succeed_msg {
    width: 500px;
    height: 470px;
    padding: 10px;
    background: #fff;
    box-sizing: border-box;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.14901960784313725);
    border-radius: 5px;
    .logo {
      width: 47px;
    }
    .succeed_msg_content {
      text-align: center;
      margin-top: 50px;
      img {
        width: 73px;
        margin-top: 20px;
      }
      p {
        @include font(rgba(0, 0, 0, 0.847), 24, 32);
        font-weight: 650;
      }
      a {
        display: block;
        margin: 0 auto;
        margin-top: 30px;
        width: 140px;
        height: 40px;
        @include font(#fff, 13, 40);
        background-color: rgb(0, 121, 254);
        border-radius: 3px;
      }
    }
  }
  .footer {
    position: absolute;
    bottom: 40px;
    font-size: 11px;
    color: rgb(204, 204, 204);
  }
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

:deep(.el-form-item__content) {
  position: relative;

  .left_msg_img {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1;
    width: 20px;
    height: 20px;
    object-fit: contain;
  }

  // .el-input__inner {
  //     padding-left: 10px;
  // }
}
</style>
